package main

import (
	"github.com/gin-gonic/gin"
	"net/url"
	"fmt"
)

func uploadFileForEncrypt(c *gin.Context) {
	key := c.PostForm("key")
	if c.PostForm("key_retype") != key {
		c.JSON(400, gin.H{"msg": "key is not match"})
		return
	}

	fh, err := c.FormFile("file")
	if err != nil {
		c.JSON(400, gin.H{"msg": "bad file format"})
		return
	}

	aesKey, iv, err := opensslAes256cbcNoSaltMd5(key)
	if err != nil {
		c.JSON(500, gin.H{"msg": "fail to opensslAes256cbcNoSaltMd5"})
		return
	}

	filename := fh.Filename
	file, err := fh.Open()
	if err != nil {
		c.JSON(500, gin.H{"msg": "cannot open upload file"})
		return
	}
	defer file.Close()

	fileLen := fh.Size

	fmt.Println("file length: ", fileLen)
	fmt.Println("Content-Length: ", fileLen-fileLen%16+16)
	r := new(aes256CbcStreamEncrypt)
	r.Init(aesKey, iv, file, fileLen-fileLen%16+16)

	extraHeaders := make(map[string]string)
	extraHeaders["Content-Disposition"] = "attachment; filename* = UTF-8''" +
		url.QueryEscape(filename) + ".aes"
	c.DataFromReader(200, fileLen-fileLen%16+16,
		"application/octet-stream", r, extraHeaders)
}

func uploadFileForDecrypt(c *gin.Context) {
	key := c.PostForm("key")

	fh, err := c.FormFile("file")
	if err != nil {
		c.JSON(400, gin.H{"msg": "bad file format"})
		return
	}

	aesKey, iv, err := opensslAes256cbcNoSaltMd5(key)
	if err != nil {
		c.JSON(500, gin.H{"msg": "fail to opensslAes256cbcNoSaltMd5"})
		return
	}

	filename := fh.Filename
	file, err := fh.Open()
	if err != nil {
		c.JSON(500, gin.H{"msg": "cannot open upload file"})
		return
	}
	defer file.Close()

	fileLen := fh.Size

	fmt.Println("file length: ", fileLen)
	fmt.Println("Content-Length: ", fileLen)
	r := new(aes256CbcStreamDecrypt)
	r.Init(aesKey, iv, file, fileLen)

	extraHeaders := make(map[string]string)
	extraHeaders["Content-Disposition"] = "attachment; filename* = UTF-8''" +
		url.QueryEscape(filename) + ".decrypted"
	c.DataFromReader(200, -1, // 无法预测解密后数据大小， contentLength 只能设为 -1
		"application/octet-stream", r, extraHeaders)
}
